package com.haika.demo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.weibo.net.AccessToken;
import com.weibo.net.DialogError;
import com.weibo.net.Utility;
import com.weibo.net.Weibo;
import com.weibo.net.WeiboDialogListener;
import com.weibo.net.WeiboException;

public class MainActivity extends Activity {

	private static final String TAG = "MainActivity";
	private static final String CONSUMER_KEY = "3419758334";
	private static final String CONSUMER_SECRET = "340ca0fe721d89c0a1d34085acd19ad9";
	private static final String URL_ACTIVITY_CALLBACK = "http://open.weibo.com/";
	private Button btn;
	private Weibo weibo;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (Button)findViewById(R.id.share);
        weibo = Weibo.getInstance();
        
        btn.setOnClickListener(new OnClickListener(){
        	public void onClick(View v){
        		weibo.setupConsumerConfig(CONSUMER_KEY, CONSUMER_SECRET);
        		weibo.setRedirectUrl(URL_ACTIVITY_CALLBACK);
        		weibo.authorize(MainActivity.this, new AuthDialogListener());
        	}
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		Utility.clearCookies(this);
		super.onDestroy();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}
    
	class AuthDialogListener implements WeiboDialogListener{

		@Override
		public void onComplete(Bundle values) {
			// TODO Auto-generated method stub
			String token = values.getString("access_token");
			String expires_in = values.getString("expires_in");
			Log.e(TAG, "token = " + token + "  expires_in = " + expires_in);
			
			AccessToken accessToken = new AccessToken(token, CONSUMER_SECRET);
			Weibo.getInstance().setAccessToken(accessToken);
			
			Intent intent = new Intent();
			intent.setClass(MainActivity.this, DemoShareActivity.class);
			startActivity(intent);
			
		}

		@Override
		public void onWeiboException(WeiboException e) {
			// TODO Auto-generated method stub
			Toast.makeText(getApplicationContext(), "Auth Exception:" + e.getMessage(), Toast.LENGTH_LONG).show();
		}

		@Override
		public void onError(DialogError e) {
			// TODO Auto-generated method stub
			Toast.makeText(getApplicationContext(), "Auth error:" + e.getMessage(), Toast.LENGTH_LONG).show();
		}

		@Override
		public void onCancel() {
			// TODO Auto-generated method stub
			Toast.makeText(getApplicationContext(), "Auth canncle", Toast.LENGTH_LONG).show();
		}
		
	}
}
